package com.pearlsoft.webapp.sysmgr.user;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;

import com.pearlsoft.commons.security.CoderUtil;
import com.pearlsoft.commons.security.DSACoder;
import com.pearlsoft.commons.utils.StringUtil;
import com.pearlsoft.commons.utils.UUIDUtil;
import com.pearlsoft.webapp.core.WebException;
import com.pearlsoft.webapp.core.annotation.DataSetHandlerComponent;
import com.pearlsoft.webapp.core.dataset.DataSet;
import com.pearlsoft.webapp.core.dataset.Record;
import com.pearlsoft.webapp.core.dataset.Result;
import com.pearlsoft.webapp.core.dataset.spi.ContextDataSetHandler;
import com.pearlsoft.webapp.core.web.session.SessionProfile;
import com.pearlsoft.webapp.core.web.util.HttpUtil;

@DataSetHandlerComponent(name = "SysUserDataSetHandler")
public class SysUserDataSetHandler extends ContextDataSetHandler {

	public void handler(DataSet ds, Result result) throws Exception {
		// TODO Auto-generated method stub

	}
	
	public void save(final DataSet ds, Result result) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		while(ds.next()){
			Record record = ds.getCurrentRecord();
			String userId =(String)record.getValue("USER_ID");
			String userCode = (String)record.getValue("USER_CODE");
			boolean isCodeDup = this.checkCodeDup(userId,userCode );
			if( isCodeDup ){
				throw new WebException("用户编码已经存在");
			}
			if(StringUtil.isEmpty(userId)){
				this.insert(record, result,jdbcTemplate);
			}else{
				this.update(record, result,jdbcTemplate);
			}
		}
		
	}
	
	public void insert(final Record record, Result result,JdbcTemplate jdbcTemplate) throws Exception {
		final String password = new String(CoderUtil.encryptMD5((System.getProperty("SYS_PASSWORD")).getBytes()),"utf-8");

		String sql = "insert into SYS_USER(USER_ID,ORG_ID,USER_CODE,USER_NAME,USER_PASSWORD,USER_TYPE,USER_SEX,USER_TEL,USER_EMAIL,USER_AVIDATE,C_STATUS,C_REMARK) values(?,?,?,?,?,?,?,?,?,?,?,?)";
			jdbcTemplate.update(sql, new PreparedStatementSetter() {
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(1, UUIDUtil.get());
					ps.setString(2, (String) record.getValue("ORG_ID"));
					ps.setString(3, (String) record.getValue("USER_CODE"));
					ps.setString(4, (String) record.getValue("USER_NAME"));
					ps.setString(5, password);
					ps.setString(6, "1");
					ps.setString(7, (String) record.getValue("USER_SEX"));
					ps.setString(8, (String) record.getValue("USER_TEL"));
					ps.setString(9, (String) record.getValue("USER_EMAIL"));
					ps.setString(10, (String) record.getValue("USER_AVIDATE"));
					ps.setString(11, (String) record.getValue("C_STATUS"));
					ps.setString(12, (String) record.getValue("C_REMARK"));
				}

			});
	}
	
	public void update(final Record record, Result result,JdbcTemplate jdbcTemplate) throws Exception {
		String sql = "update SYS_USER set ORG_ID=?,USER_CODE=?,USER_NAME=?,USER_SEX=?,USER_TEL=?,USER_EMAIL=?,USER_AVIDATE=?,C_STATUS=?,C_REMARK=? where USER_ID=?";
		jdbcTemplate.update(sql, new PreparedStatementSetter() {
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setObject(1, record.getValue("ORG_ID"));
				ps.setObject(2, record.getValue("USER_CODE"));
				ps.setObject(3, record.getValue("USER_NAME"));
				ps.setObject(4, record.getValue("USER_SEX"));
				ps.setObject(5, record.getValue("USER_TEL"));
				ps.setObject(6, record.getValue("USER_EMAIL"));
				ps.setObject(7, record.getValue("USER_AVIDATE"));
				ps.setObject(8, record.getValue("C_STATUS"));
				ps.setObject(9, record.getValue("C_REMARK"));
				ps.setObject(10, record.getValue("USER_ID"));
			}
		});

	}
	public void resetPwd(final DataSet ds, Result result) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		final String password = new String(CoderUtil.encryptMD5((ds.getConditions().get("password")).toString().getBytes()),"utf-8");
		String sql = "update SYS_USER set USER_PASSWORD=? where USER_ID=?";
		while (ds.next()) {
			jdbcTemplate.update(sql, new PreparedStatementSetter() {
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(1, password);
					ps.setString(2, (String) ds.getValue("objId"));
				}
			});
			
		}
	}
	public void delete(final DataSet ds, Result result) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql = "delete from SYS_USER where USER_ID=?";
		while (ds.next()) {
			jdbcTemplate.update(sql, new PreparedStatementSetter() {
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(1, (String) ds.getValue("objId"));
				}
			});
			
		}
		
	}
	public boolean checkCodeDup(String userid,String userCode){
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql ="";
		Map<String,String> params = new HashMap<String,String>();
		Object[] objects =null;
		if( StringUtils.isBlank(userid)){
			sql =" select count(*) from SYS_USER where user_code =?";
			objects = new Object[]{userCode};
			params.put("user_code", userCode);
		}else{
			sql =" select count(*) from SYS_USER where user_code =? and user_id <>?";
			objects = new Object[]{userCode,userid};
		}
		int count = jdbcTemplate.queryForInt(sql, objects);
		return count > 0 ? true:false;
		
	}
	
	public void deleteUserUrl(final DataSet ds, Result result) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		final SessionProfile profile = HttpUtil.getUserProfile(this.getSession());
		final String menuId = (String) ds.getValue("MENU_ID");
		final String userId  = profile.getUserId();
		String sql = "delete from SYS_USER_URL where MENU_ID=? AND  USER_ID=?";
		jdbcTemplate.update(sql, new PreparedStatementSetter() {
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, menuId);
				ps.setString(1, userId);
			}
		});
	}
	
	public void saveUserUrl(final DataSet ds, Result result) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql = "INSERT INTO SYS_USER_URL(USER_URL_ID,MENU_ID,USER_ID) values(?,?,?)";
		final SessionProfile profile = HttpUtil.getUserProfile(this.getSession());
		final String menuId = (String) ds.getValue("MENU_ID");
		final String userId  = profile.getUserId();
		if(checkUserUrl(userId,menuId)){
			throw new WebException("已经加入快捷菜单.");
		}
		jdbcTemplate.update(sql, new PreparedStatementSetter() {
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setObject(1, UUIDUtil.get());
				ps.setObject(2, menuId);
				ps.setObject(3,userId);
			}
			
		});
	}
	
	private boolean checkUserUrl(String userId,String menuId){
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql =" select count(*) from SYS_USER_URL where USER_ID=? and MENU_ID =?";
		int count = jdbcTemplate.queryForInt(sql);
		return  count > 0 ? true:false;
	}
	

}
